package cn.zj.smart.util;



import cn.zj.smart.util.base.IdEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * @author xi.yang
 * @create 2020-03-25 16:57
 **/
public class EnumUtil {
    private static final Logger logger = LoggerFactory.getLogger(EnumUtil.class);

    private static final Map<String, Map<Integer, IdEnum>> cache = new HashMap<>();

    /**
     * 根据id获取IdEnum类型的具体enum
     * @param enumType
     * @param id
     * @param <T>
     * @return
     */
    public static <T extends IdEnum> T getIdEnum(Class<T> enumType, int id) {
        final String enumClass = enumType.getName();
        Map<Integer, IdEnum> ts = cache.get(enumClass);
        if (null == ts) {
            logger.warn("init ....");
            ts = new HashMap<>();
            IdEnum[] enums = enumType.getEnumConstants();
            for (IdEnum anEnum : enums) {
                ts.put(anEnum.getId(), anEnum);
            }
            cache.put(enumClass, ts);
        }
        T result = (T) cache.get(enumClass).get(id);
        if (null == result) {
            logger.error("not found enum[{}] id[{}]", enumType, id);
        }
        return result;
    }

}
